package com.zp.security.oauth2.config;

import com.zp.security.oauth2.customized.EmailTokenGranter;
import com.zp.security.oauth2.exception.MyClientCredentialsTokenEndpointFilter;
import com.zp.security.oauth2.exception.MyWebResponseExceptionTranslator;
import com.zp.security.oauth2.exception.OAuthServerAuthenticationFailureHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * OAuth2.0授权服务器配置
 *
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    /**
     * 客户端存储策略，这里使用内存方式，后续可以存储在数据库
     */
    @Resource
    private ClientDetailsService clientDetailsService;
    /**
     * 令牌存储策略
     */
    @Resource
    private TokenStore tokenStore;
    /**
     * Security的认证管理器，密码模式需要用到
     */
    @Resource
    private AuthenticationManager authenticationManager;
    /**
     * 令牌的转换策略
     */
    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Resource
    private OAuthServerAuthenticationFailureHandler oAuthServerAuthenticationFailureHandler;
    @Resource
    private MyWebResponseExceptionTranslator myWebResponseExceptionTranslator;

    @Resource
    private DataSource dataSource;

    /**
     * 授权码模式的service，使用授权码模式authorization_code必须注入
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        //适用jdbc的方式从数据库中获取
        return new JdbcAuthorizationCodeServices(dataSource);
    }
    /**
     * 安全约束配置配置
     *
     */
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

        //客户端密码认证门户过滤器
        MyClientCredentialsTokenEndpointFilter myClientCredentialsTokenEndpointFilter = new MyClientCredentialsTokenEndpointFilter(security,oAuthServerAuthenticationFailureHandler);
        //将自定义的认证处理失败和成功逻辑设置进过滤器
        myClientCredentialsTokenEndpointFilter.afterPropertiesSet();
        /**
         * /oauth/authorize：获取授权码的端点
         * /oauth/token：获取令牌端点。
         * /oauth/confifirm_access：用户确认授权提交端点。
         * /oauth/error：授权服务错误信息端点。
         * /oauth/check_token：用于资源服务访问的令牌解析端点。
         * /oauth/token_key：提供公有密匙的端点，如果你使用JWT令牌的话。
         * */
        //为某些端点开放权限
        security
                //开启/oauth/token_key验证端口权限访问
                .tokenKeyAccess("permitAll()")
                //开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess("permitAll()")
                //表示支持 client_id 和 client_secret 做登录认证
                //.allowFormAuthenticationForClients()
                //使用自定义的认证Filter
                .addTokenEndpointAuthenticationFilter(myClientCredentialsTokenEndpointFilter);
    }

    /**
     * 客户端配置,配置允许接入客户端等
     *
     */
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //使用JdbcClientDetailsService，从数据库中加载客户端的信息
        clients.withClientDetails(new JdbcClientDetailsService(dataSource));
    }

    /**
     * 令牌管理服务的配置
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        //客户端端配置策略
        services.setClientDetailsService(clientDetailsService);
        //支持令牌的刷新
        services.setSupportRefreshToken(true);
        //令牌服务
        services.setTokenStore(tokenStore);
        //access_token的过期时间
        services.setAccessTokenValiditySeconds(60 * 60 * 2);
        //refresh_token的过期时间
        services.setRefreshTokenValiditySeconds(60 * 60 * 24 * 3);
        //设置令牌的转换策略将jwt和Oauth2的认证信息转换
        services.setTokenEnhancer(jwtAccessTokenConverter);
        return services;
    }

    /**
     * 令牌端点配置
     *
     */
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)  {


        //获取所有的tokenGranters加入新的EmailTokenGranter
        List<TokenGranter> tokenGranters=new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
        tokenGranters.add(new EmailTokenGranter(authenticationManager,tokenServices(),clientDetailsService,new DefaultOAuth2RequestFactory(clientDetailsService)));

        endpoints
                //自定义异常翻译器
                .exceptionTranslator(myWebResponseExceptionTranslator)
                //授权码模式所需要的authorizationCodeServices
                .authorizationCodeServices(authorizationCodeServices())
                //密码模式所需要的authenticationManager
                .authenticationManager(authenticationManager)
                //令牌管理服务，无论哪种模式都需要
                .tokenServices(tokenServices())
                //为了将自定自定义的email模式加入到CompositeTokenGranter
                .tokenGranter(new CompositeTokenGranter(tokenGranters))
                //只允许POST提交访问令牌，uri：/oauth/token
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

}
